package com.tech.connect.view;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.tech.connect.R;


public class SideBar extends View {
    private IndexListener indexListener;
    public static String[] indexs = {"#", "☆", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};
    private int choose = -1;// 选中
    private Paint paint = new Paint();


    public SideBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SideBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SideBar(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int height = getHeight();
        int width = getWidth();
        int singleHeight = height / indexs.length;
        for (int i = 0; i < indexs.length; i++) {
            paint.reset();
            paint.setColor(getResources().getColor(R.color.common_colorBlue));
            paint.setAntiAlias(true);
            paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12f, getResources().getDisplayMetrics()));
            if (i == choose) {
                paint.setColor(getResources().getColor(R.color.common_colorOrange));
            }
            float xPos = width / 2 - paint.measureText(indexs[i]) / 2;
            float yPos = singleHeight * i + singleHeight;
            canvas.drawText(indexs[i], xPos, yPos, paint);
        }

    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();
        final float y = event.getY();
        final int oldChoose = choose;
        final int c = (int) (y / getHeight() * indexs.length);

        switch (action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                if (oldChoose != c) {
                    if (c >= 0 && c < indexs.length) {
                        if (indexListener != null) {
                            indexListener.onIndexAt(indexs[c]);
                        }
                        choose = c;
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                choose = -1;
                invalidate();
                break;
        }
        return true;
    }

    public void setIndexListener(IndexListener indexListener) {
        this.indexListener = indexListener;
    }


    public interface IndexListener {
        void onIndexAt(String index);
    }

}